package com.jc.common.redis.trans;

import java.util.List;

import org.apache.log4j.Logger;

import com.jc.common.redis.MyRedisException;
import com.jc.common.redis.RedisTemplate;

public class RedisTransaction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(RedisTransaction.class);

	private RedisTemplate template;

	public RedisTransaction(RedisTemplate template) {
		this.template = template;
	}
	
	public RedisTransactionStatus init(String... keys)  throws MyRedisException{
		RedisTransactionStatus ts = new RedisTransactionStatus(template.getJedis(),keys);
		return ts;
	}
	
	public void destroy(RedisTransactionStatus ts) throws MyRedisException{
		try {
			if (ts != null && ts.getRedis() != null){
				ts.getRedis().unwatch();
			}
		} catch (Exception e) {
			throw new MyRedisException(e);
		}finally{
			release(ts);
		}
	}
	
	public void begin(RedisTransactionStatus ts)  throws MyRedisException{
		ts.setTransaction(template.mutil(ts.getRedis()));
	}
	
	public List<Object> commit(RedisTransactionStatus ts) throws MyRedisException{
		List<Object> result = null;
		try {
			result = ts.getTransaction().exec();
		} catch (Exception e) {
			throw new MyRedisException(e);
		}finally{
			release(ts);
		}
		return result;
		
	}
	
	public void rollback(RedisTransactionStatus ts) throws MyRedisException{
		try {
			ts.getTransaction().discard();
		} catch (Exception e) {
			throw new MyRedisException(e);
		}finally{
			release(ts);
		}
		
	}
	
	/**
	 * 
	 * @param ts
	 */
	private void release(RedisTransactionStatus ts){
		try {
			if (ts != null && ts.getRedis() != null){
				template.getRedisPool().returnResource(ts.getRedis());
				ts.cleanRedis();
			}
		} catch (Exception e) {
			logger.warn("release(RedisTransactionStatus) - exception ignored", e); 
			
		}
	}
	
}
